#!/bin/bash

cwd=`dirname $0`
. $cwd/scripts/common.sh


uboot_copy_flag=0
kernel_copy_flag=0

copy_uboot()
{
    if [ -d $SDCARDDIR ];then
        echo "update uboot to $SDCARDDIR"
        cp $OUTPUT_UBOOTDIR/MLO  $SDCARDDIR/MLO_NAND
        cp $OUTPUT_UBOOTDIR/u-boot.img $SDCARDDIR/u-boot_NAND.img
        cp $OUTPUT_UBOOTDIR/u-boot.img $SDCARDDIR/u-boot.img
        sync
        sync
        sync
    fi

    echo "update uboot to $TFTPDIR"
    cp $OUTPUT_UBOOTDIR/u-boot.img $TFTPDIR/u-boot_NAND.img
    cp $OUTPUT_UBOOTDIR/u-boot.img $TFTPDIR/u-boot.img
    cp $OUTPUT_UBOOTDIR/MLO  $TFTPDIR/MLO_NAND
    cp $OUTPUT_UBOOTDIR/MLO  $TFTPDIR/MLO

    echo "copy uboot to $IMAGEDIR/uboot_$UBOOT_VERSION"
    mkdir -p $IMAGEDIR/uboot_$UBOOT_VERSION
    cp $OUTPUT_UBOOTDIR/u-boot.img $IMAGEDIR/uboot_$UBOOT_VERSION/uboot.$UBOOT_VERSION
    cp $OUTPUT_UBOOTDIR/MLO  $IMAGEDIR/uboot_$UBOOT_VERSION/MLO.$UBOOT_VERSION

    echo "copy uboot to $ROOTFSDIR"
    cp $OUTPUT_UBOOTDIR/MLO $ROOTFSDIR/home/root/update/img/MLO_NAND
    cp $OUTPUT_UBOOTDIR/u-boot.img        $ROOTFSDIR/home/root/update/img/u-boot_NAND.img

}
copy_kernel()
{
    if [ -d $SDCARDDIR ];then
        echo "update kernel&dtb to $SDCARDDIR"
        cp $OUTPUT_KERNEL/uImage  $SDCARDDIR
        cp $OUTPUT_KERNEL/dts/am335x-evmsk.dtb $SDCARDDIR/amxx5x-evmsk.dtb
        cp $OUTPUT_KERNEL/dts/am335x-evmsk.dtb $SDCARDDIR/
        sync
        sync
        sync
    fi
    echo "update kernel&dtb to $TFTPDIR"
    cp $OUTPUT_KERNEL/uImage  $TFTPDIR
    cp $OUTPUT_KERNEL/dts/am335x-evmsk.dtb $TFTPDIR

    echo "copy kernel to $IMAGEDIR/kernel_$KERNEL_VERSION"
    mkdir -p $IMAGEDIR/kernel_$KERNEL_VERSION
    cp $OUTPUT_KERNEL/uImage  $IMAGEDIR/kernel_$KERNEL_VERSION/kernel.$KERNEL_VERSION
    cp $OUTPUT_KERNEL/dts/am335x-evmsk.dtb $IMAGEDIR/kernel_$KERNEL_VERSION/dts.$KERNEL_VERSION

    echo "copy kernel&dts to $ROOTFSDIR"
    cp $OUTPUT_KERNEL/uImage $ROOTFSDIR/home/root/update/img
    cp $OUTPUT_KERNEL/dts/am335x-evmsk.dtb $ROOTFSDIR/home/root/update/img
}
make_uboot()
{
    make u-boot
}
make_kernel()
{
    make linux
    make linux-dtbs
}

if [ $# -le 0 ];then
    echo "[Useage:  update  kernel or uboot ?]"
    exit 0
fi

if [ $1 = "kernel" ];then
    if [ $# -gt 1 ] && [ $2 = "copy" ];then 
        echo "Only copy uImage & dtbs"
    else
        make_kernel
    fi
    kernel_copy_flag=1
fi

if [ $1 = "uboot" ];then
    if [ $# -gt 1 ] && [ $2 = "copy" ];then 
        echo "Only copy MLO & u-boot.img"
    else
        make_uboot
    fi
    uboot_copy_flag=1
fi

if [  -d $SDCARDDIR ];then
    echo "SDCard is exist!"
fi

if [ $kernel_copy_flag -eq 1 ];then
    echo "Updating uImage & dtb"
    copy_kernel
fi
if [ $uboot_copy_flag -eq 1 ];then
    echo "Updating MLO & u-boot.img"
    copy_uboot
fi
echo "OK!"
